"use client";
import { PropsWithChildren, useEffect, useRef, useState } from "react";
import style from "./index.module.css";
import { cn } from "@/lib/util";
import { BaseChildrenProps } from "@/types/baseProps";

interface AutoScrollProps extends BaseChildrenProps {
  /**内一层的className */
  innerClassName?: string;
  /**动画时间，单位s */
  duration?: number;
  /**在可以滚动的时候，是否允许滚动，默认true */
  scroll?: boolean;
}

/**超出父组件长度，自动左右滚动组件 */
export default function AutoScroll({ duration, children, innerClassName, className, scroll = true }: AutoScrollProps) {
  /**组件外层部分 */
  const outer = useRef<HTMLDivElement>(null);
  /**组件内层部分 */
  const inner = useRef<HTMLDivElement>(null);
  const [paused, setPaused] = useState(true); // 是否暂停动画
  const [client, setClient] = useState(false); //当前是否是客户端。是的话才渲染孩子，不然会报水合错误
  const [scrollSpeed, setScrollSpeed] = useState(1); //播放速度倍速（基础时间是2s）
  useEffect(() => {
    setClient(true);
  }, []);
  useEffect(() => {
    const innerWidth = inner.current?.clientWidth || 1;
    const outerWidth = outer.current?.clientWidth || 1;
    //比较当前是否比父元素宽度要大，是的话才执行动画
    if (innerWidth > outerWidth) {
      setPaused(false);
      setScrollSpeed(innerWidth / outerWidth);
    }
  }, [client, children]);
  return (
    <div ref={outer} className={cn(style.scrollWrap, className)}>
      <div
        ref={inner}
        className={cn(innerClassName, style.scrollItem)}
        style={{
          animationPlayState: !paused && scroll ? "running" : "paused",
          animationDuration: `${duration || scrollSpeed * 2}s`,
        }}
      >
        {client && children}
      </div>
    </div>
  );
}
